<?php

namespace core;

class Url
{
    private static $url_pattern = true;     //传统模式
    private static $url_suffix = 'html';    //后缀
    private static $url_separator = '/';    //分隔符

    /**
     * URL生成
     * @param string $str
     * @param array $ary
     * @return string
     */
    public static function create(string $str = '', array $ary = []): string
    {
        if (self::$url_pattern) {
            //传统模式
            $val_splicer = '=';
            $val_suffix = '&';

            $url_splicer = '.' . self::$url_suffix . '?';
            $url_suffix = '';
        } else {
            //优化模式
            $val_splicer = '/';
            $val_suffix = '/';

            $url_splicer = '/';
            $url_suffix = '.' . self::$url_suffix;
        }

        if ($str != '') {
            //生成指定url
            if (0 !== strpos($str, '/')) {
                //相对路径(需补全)
                $strAry = explode('/', $str);
                $strAryNum = count($strAry);

                if ($strAryNum == 1) {
                    $url = request()->module() . self::$url_separator . request()->controller() . self::$url_separator . $str;
                } elseif ($strAryNum == 2) {
                    $url = request()->module() . self::$url_separator . $str;
                } else {
                    $url = $str;
                }
                $url = '/' . $url;
            } else {
                //指定路径
                $url = $str;
            }
        } else {
            //生成当前页面url
            $url = request()->baseUrl();
            $action = request()->action();
            $urlAry = explode('/' . $action, $url);
            $url = $urlAry[0] . '/' . $action;
        }

        if (!empty($ary)) {
            $vals = '';
            //参数串按队生成
            foreach ($ary as $k => $val) {
                if ($val != null) {
                    $vals .= $k . $val_splicer . urlencode(mb_convert_encoding($val, 'utf-8', 'auto')) . $val_suffix;
                }
            }
            $vals = rtrim($vals, '&');
            $vals = rtrim($vals, '/');
            $url = $url . $url_splicer . $vals . $url_suffix;
        } else {
            $url = $url . '.' . self::$url_suffix;
        }

        return $url;
    }

}